﻿function collectData_Initiate(sDraftXml,sResultXml) {
    var context = XMLDOM();
    var result = XMLDOM();
    
    context.loadXML(sDraftXml);
    result.loadXML(sResultXml)
    for(var i=0;i<result.documentElement.childNodes.length-1;i++)
    {
        if (result.documentElement.childNodes[i].nodeName == "Handle" )
            context.documentElement.replaceChild(result.documentElement.childNodes[i],context.selectSingleNode("/Context/Handle"));
        else
            context.documentElement.appendChild(result.documentElement.childNodes[i]);
        
    }
    
    root = context.selectSingleNode("/Context/Params");    
    
    //1.6 DocHtml
    var handType = context.selectSingleNode("/Context/Handle");
    if(handType.attributes.getNamedItem("type").value == "ApprovePass" && handType.selectSingleNode("Action").attributes.getNamedItem("type").value == "Book")
    {
        var doc = context.createNode(1, "DocHtml", "");
        if (appForm.DocumentType.value == 0) {
            //去除边框
            if (!_objFormContext.styleSheets.length) _objFormContext.createStyleSheet();
            with (_objFormContext.styleSheets(_objFormContext.styleSheets.length - 1)) {
                addRule("input", "border:0px;");
            }
            //去除脚本
            for (var i = 0; i < _objFormContext.scripts.length; i++) {
                _objFormContext.scripts[i].clearAttributes();
            }
            doc.text = deleteEvent(_objFormContext.documentElement.innerHTML.replace(/<SCRIPT><\/SCRIPT>/g, ""));
        }
        else if (appForm.DocumentType.value == 2) {
            //扩展表单
            doc.text = deleteEvent(objContext.document.documentElement.innerHTML);
        }
        root.appendChild(params);
    }   
    
    //alert(context.xml)    
    return context.xml;
}

function collectData_SaveDraft() {
    var data = new StringBuilder();	
    
    data.append("<Context><Handle type='Initiate'><Action type=''>");
    data.append("<Auditors><User guid='"+$id("txtUserGUID").value+"' name='"+$id("txtUserName").value+"'/></Auditors></Action></Handle>");

    data.append("<Params>");
    data.append("<IsNew>" + (sProcessStatus == ""? "1" : "0") + "</IsNew>");
    data.append("<HandleText>"+ $id("txtHandleText").value + "</HandleText>");
    data.append("<StationGUID>"+ Station.returnValue + "</StationGUID>");
    data.append("<ProcessGUID>"+ appForm.ProcessGUID.value + "</ProcessGUID>");
    data.append("<ProcessName>"+ appForm.ProcessName.value + "</ProcessName>");
    data.append("<ProcessNo>"+ appForm.ProcessNo.value + "</ProcessNo>");
    data.append("<ProcessLevel>"+ appForm.ProcessLevel.value + "</ProcessLevel>");
    data.append("<PMGUID>"+ appForm.ProcessModuleGUID.value + "</PMGUID>");
    data.append("<BusinessGUID>"+ appForm.BusinessGUID.value + "</BusinessGUID>");
    data.append("<BusinessType>"+ appForm.BusinessType.value + "</BusinessType>");
    data.append("<D_Original>"+ appForm.D_Original.value + "</D_Original>"); 
    data.append("<WatchMembers>"+ appForm.WatchMembers.value + "</WatchMembers>"); 
    data.append("<WatchMembersName>"+ appForm.WatchMembersName.value + "</WatchMembersName>"); 
    data.append("<ProcessSerialNumber>"+ appForm.ProcessSerialNumber.value + "</ProcessSerialNumber>"); 
    data.append("<DomainXml>"+ HtmlEncode(oprGetDomainXml()) + "</DomainXml>");
     
    data.append("</Params></Context>");
    
    return data.toString();
}
//获取域XML
function oprGetDomainXml()
{
    var domain="";
	switch($id("txtDocumentType").value)
	{
		case "0": //业务表单
			domain = SetHTMLDomainXMLValue(_objFormContext,document.all("txtDomainXML").value,document.all("txtEditBusinessDomain").value);
			break;
			
		case "2": //扩展表单		
	        domain = document.frames("appIframe_HtmlForm").GetXML(document.all("txtDomainXML").value)
			break;
	}	
	return domain;
}

/*-------------------------------------------------------------业务逻辑相关-----------------------------------------------------------------------------*/
function SaveApproveBill(docType)
{
    if ( docType == "0")
    {   
        var dataXML = new StringBuilder();
	
		//业务表单
		dataXML.append("<dataxml>");			
		dataXML.append("<doc docName=\""+appForm.ProcessName.value+"\" buGUID=\""+appForm.BUGUID.value+"\" docGUID=\"" + appForm.D_Original.value + "\">" + HtmlEncode($id("txtOriginalHTML").value) + "</doc>");			
		dataXML.append("</dataxml>");
        var result = saveData("SAVEDOC",dataXML.toString());
        if (result == "-1")
        {
            alert("保存审批表单失败，请与系统管理员联系！");
            return false;
        }
    }
    else
    {
       
        //初始化Http引擎
        document.all.oframe.HttpInit();
        //增加Post变量
        document.all.oframe.HttpAddPostString("DocumentGUID",appForm.D_Original.value);
        document.all.oframe.HttpAddPostString("ProcessGUID" ,appForm.ProcessGUID.value);
        document.all.oframe.HttpAddPostString("LastStationGUID" ,appForm.StationGUID.returnValue);
        document.all.oframe.HttpAddPostString("DocumentSource" ,"ProcessDraft");
        document.all.oframe.HttpAddPostString("DocumentType" ,sDocType);
        document.all.oframe.HttpAddPostString("DocumentName" ,appForm.ProcessName.value);
        	
        //上传打开的文件
        document.all.oframe.HttpAddPostCurrFile("FileData", (sDocType=="1"?"blank.doc":"blank.xls"));
        //执行上传动作
        document.all.oframe.HttpPost(document.URL.substring(0,document.URL.lastIndexOf("/")) + "/WF_Document_Save.aspx"); 
     }
     return true;
}
function verify(type)
{
    if(!bSetupOffice){
        alert("客户端没有安装Office软件，不允许使用此功能！");
        return false;
    }
    /*---------------------------------*/
    if (type=="Initiate")
    {
        if(Station.returnText == "") {
            alert("请选择\"岗位\"！");
            event.returnValue = false;
            return false;
        }
        if ($id("txtHandleText").value=="")
	    {
	        alert("处理意见不能为空!");
	        return undefined;
	    }	    
	}
	/*---------------------------------*/
    if(!ValidateRepeate()){
        return false;
    }
    
    return true;
}
function saveData(method,data)
{
    sReturnValue = GetDataFromXMLHTTP("/MyWorkflow/WF_Engine_XmlHttp.aspx",method,"","",data);
    return sReturnValue ;
}

// 保存草稿
function saveDraft()
{
    //保存前校验    
    if (!verify())  return;
    
    var data;
    //收集数据
	data = collectData_SaveDraft()
	
	if (sProcessStatus == "") //新流程
	{
	    //需要保存表单
	    if (!SaveApproveBill(sDocType)) return;
	}
	else if(sDocType=="1"||sDocType=="3") //之前存有草稿
	{
	    //需要保存表单
	    if (!SaveApproveBill(sDocType )) return;
	}
	
	//保存数据
	sReturnValue = saveData("SAVEDRAFT",data);
		
	if(sReturnValue=="-1") return;
	
	var xmlDom = XMLDOM();
	
	xmlDom.loadXML(sReturnValue);
	
	if(xmlDom.documentElement.attributes.getNamedItem("result").value == "false" )
	{
		alert( xmlDom.documentElement.attributes.getNamedItem("errormessage").value);
	}
	else
	{
		appForm.setFormDefaultValue();
		_bProcessSaved = true;
		
		if(confirm("保存草稿成功，可以到『我发起的流程』模块查看该流程。是否关闭当前窗口？"))
		{
			try{
				opener.afterWorkflow(appForm.ProcessGUID.value);
			} catch(e){};
			window.close();
		}
		else
		{
		
			if($id("__mode").value == "1")
				window.navigate("/MyWorkflow/WF_ProcessInitiate_Form.aspx?mode=2&oid=" + appForm.ProcessGUID.value);
				
			try{
				opener.afterWorkflow(appForm.ProcessGUID.value);
			} catch(e){};
			
		}
	}
}
// 发起流程
function initiateProcess()
{
    //保存前校验    
    if (!verify("Initiate")) return;
    
    var sDomainXML = oprGetDomainXml();
    var data="";
    
    if (!CompareBizData(sDomainXML))
        return false;

    var xmlDom = XMLDOM();
    
        
    //如果为新流程，则需要先进行保存草稿的操作
    if (sProcessStatus == "")          //新流程
	{   
	    //收集数据
	    data = collectData_SaveDraft();
	    //保存表单
	    if (!SaveApproveBill(sDocType)) return;
	    //保存数据
	    sReturnValue = saveData("SAVEDRAFT",data);
	    
	    if(sReturnValue=="-1") return;
	    xmlDom.loadXML(sReturnValue);
	    
	    xmlDom.loadXML(sReturnValue);
	
	    if(xmlDom.documentElement.attributes.getNamedItem("result").value == "false" )
	    {
		    alert( xmlDom.documentElement.attributes.getNamedItem("errormessage").value);
		    return;
	    }
	    sCurrentStepGUID = xmlDom.documentElement.attributes.getNamedItem("stepguid").value
	    sProcessStatus = "Draft";
	}
	else if(sDocType=="1"||sDocType=="3") //之前存有草稿（且为公文）
	{
	    //需要保存表单
	    if (!SaveApproveBill(sDocType )) return;
	}
	
	sCurrentStepGUID = sCurrentStepGUID==""?$id("txtStepGUID").value:sCurrentStepGUID;
    strReturnValue = openInitGuide(sDomainXML,sCurrentStepGUID);

	if (strReturnValue != undefined)
	{
	    //收集数据
	    data = collectData_SaveDraft();
	    strReturnValue = collectData_Initiate(data,strReturnValue);
	}
	else return;
	
	
	if (!BizInitValiate())
    {
        return;
    }
	
	strReturnValue = saveData("INITIATEPROCESS",strReturnValue);
		
	if(strReturnValue=="-1") return;
	
	xmlDom.loadXML(sReturnValue);
	
	if(xmlDom.documentElement.attributes.getNamedItem("result").value == "false" )
	{
		alert( xmlDom.documentElement.attributes.getNamedItem("errormessage").value);
	}
	else
	{
		appForm.setFormDefaultValue();
		_bProcessSaved = true;
		
		alert("发起成功，可以到『我发起的流程』模块查看该流程！");

		// 刷新流程列表
		try
		{
			//sbb11
			opener.afterWorkflow(appForm.ProcessGUID.value);
		}
		catch(e){};
		
		parent.window.close();
	}	
	event.returnValue = false;
}
//修改业务数据
function UpdateBusinessData(){
    var sBusinessGUID , sBusinessURL;

	sBusinessGUID = appForm.BusinessGUID.value;
	sModifyURL = appForm.ModifyURL.value;

	if (sBusinessGUID.length>0)
	{
		if(sModifyURL.toLowerCase().indexOf("javascript")>=0)
		{
			window.execScript(sModifyURL.replace(/\[oid\]/g,"'" + sBusinessGUID + "'"),"JScript");
		}
		else
		{
			openMyFullWin(sModifyURL.replace(/\[oid\]/g,sBusinessGUID))
		}
	}
	else
	{
		alert("该流程没有对应的业务GUID!")
	}
}
//同步业务数据
function sData(){
    var method = "SDBusinessM";
    var oid = appForm.ProcessModuleGUID.value;
    if (appForm.ProcessStatus.value && appForm.ProcessStatus.value=="-3")
    {
    	method = "SDBusinessE";
    	oid = appForm.ProcessGUID.value;
    }
    //应该要用最新的BTDomainXML
    //GetNewDomainXML()
    $id("txtDomainXML").value = GetDataFromXMLHTTP("/MyWorkflow/WF_XmlHTTP.aspx",method,oid,appForm.BusinessGUID.value,"");
    switch($id("txtDocumentType").value)
	{
		case "0":
			myXmlHttp.callByAsync("/MyWorkflow/WF_Document_Get.aspx?mode=3&DocumentType=0&DocumentGUID=" + $id("txtDocumentGUID").value + "&rnd=" + Math.random(),"",loadHtmlAsync);//业务表单
			break;
		case "2":
			loadExtendFormHtml();//扩展表单
			break;
	}
}
//验证数据
function ValidateRepeate(){
    if(checkProcessName(appForm.ProcessName.value,appForm.ProcessGUID.value,appForm.ProcessModuleGUID.value)){
        alert("\"标题\"有重复，请重新输入！");
        event.returnValue=false;
        return false;
    }
    //设置了编码规则,不需要重复性校验
    if ($id("txtCodeCodingRule").value!="") return true;
    //如果编号为空,也不需要重复性校验
    if (appForm.ProcessNo.value=="") return true;
    if(checkProcessNo(appForm.ProcessNo.value,appForm.ProcessGUID.value,appForm.ProcessModuleGUID.value)){
        alert("\"编号\"有重复，请重新输入！");
        event.returnValue=false;
        return false;
    }
    return true;
}
//比较业务数据域
function CompareBizData(oldDomainXML)
{   
    //判断业务数据
    if($id("txtBusinessTypeGUID").value != "" && ($id("txtDocumentType").value=="0" || $id("txtDocumentType").value=="2")){
    
        //判断是否存在非历史流程
        if(GetDataFromXMLHTTP("/MyWorkflow/WF_XmlHTTP.aspx","BusinessIsHistory",appForm.BusinessGUID.value,appForm.ProcessModuleGUID.value,"") != "0")      {
            alert("当前流程关联的业务单据已经发起了审批，不允许重复发起！");
            return false;
        }
         var newDomainXML = "" ;
        //判断业务数据是否一致
        if (document.all("__oid"))
		    newDomainXML = GetDataFromXMLHTTP("/MyWorkflow/WF_XmlHTTP.aspx","SDBusinessE",appForm.ProcessGUID.value,appForm.BusinessGUID.value,"");
	    else
		    newDomainXML = GetDataFromXMLHTTP("/MyWorkflow/WF_XmlHTTP.aspx","SDBusinessM",appForm.ProcessModuleGUID.value,appForm.BusinessGUID.value,"");
        
        var newXmlDom = new ActiveXObject("Microsoft.XMLDOM");
        newXmlDom.loadXML(newDomainXML);
        var oldXmlDom = new ActiveXObject("Microsoft.XMLDOM");
        oldXmlDom.loadXML(oldDomainXML);
 
        var diffDomain = "";
        var newDomainNode,oldValue,newValue;
        var arrCompareDomain = $id("txtProcessCompareDomain").value.split(","); //只比较已经定义的业务数据域
        for(var i=0;i<arrCompareDomain.length;i++){
            if(arrCompareDomain[i] == "")
                break;
            newDomainNode = newXmlDom.selectSingleNode("/BusinessType/Item/Domain[@name='" + arrCompareDomain[i] + "']");
            
            if (newDomainNode){
                oldValue = oldXmlDom.selectSingleNode("/BusinessType/Item/Domain[@name='" + arrCompareDomain[i] + "']").text.replace(/(^\s*)|(\s*$)/g, "").replace(/\n/g,"");
                newValue = newDomainNode.text.replace(/(^\s*)|(\s*$)/g, "").replace(/\n/g,"");
                if( oldValue != newValue ){
                    diffDomain += "【" + arrCompareDomain[i] + "】,";
                }
            }
            else{
                //流程模板的业务对象被更改
                diffDomain += "【" + arrCompareDomain[i] + "】,";
            }
        }

        if(diffDomain.length > 0){
            var strConfirm = "审批表单中的数据与业务单据中有以下数据域不一致\r\n---------------------------------------------\r\n" + diffDomain.substring(0,diffDomain.length-1) + "\r\n--------------------------------------------\r\n是否进行提交？";
            if(!confirm(strConfirm)){
                reDisplay("cUpdateBusinessData,cSD,cLine2");
                return false;
            }
        }
    }
    return true;
}
function BizInitValiate()
{
    if($id("txtDocumentType").value=="0" || $id("txtDocumentType").value=="2"){
        if (typeof(document.frames("appIframe_HtmlForm").InitValidate)=="function")
            return document.frames("appIframe_HtmlForm").InitValidate()
    }
    return true;
}
//转换命名编码规则
function transformCoding(strCoding,control)
{
    if(strCoding.length == 0)
        return "";
    
    control.setReadOnly(true);
    SetControlReq(control,false);
           
    var returnValue;
    //替换~
    returnValue = strCoding.replace(/~/g,"");
    //替换#
    returnValue = returnValue.replace(/#/g,"");
    //替换$
    returnValue = returnValue.replace(/\$公司名称\$/g,$id("txtBUName").value);
    returnValue = returnValue.replace(/\$公司代码\$/g,$id("txtBUCode").value);
    returnValue = returnValue.replace(/\$年\$/g,$id("txtYear").value);
    returnValue = returnValue.replace(/\$月\$/g,$id("txtMonth").value);
    returnValue = returnValue.replace(/\$流水号\$/g,$id("txtNum").value);
    //替换数据域[]

    var xmlDom = XMLDOM();
    xmlDom.loadXML($id("txtDomainXML").value);
    var nodes = xmlDom.selectNodes("/BusinessType/Item/Domain");
    var _name,_value;
    
    //_objFormContext
    for(var i = nodes.length - 1;i>=0;i--)
    {
        _name = nodes[i].attributes.getNamedItem("name").value;        
        _value = nodes[i].text;
        if (_value == "" && sDocType=="1") _value = _objFormContext.getElementById(_name).value;
        returnValue = returnValue.replace(new RegExp("\\[" + _name + "\\]","g"),_value.length > 0?_value:_name);
    }
    return returnValue;
}